#encoding: utf-8
load 'rds_api.rb'
@rds = @rds_tt

# Usage: report-followup.rb keyword
# 将指定关键字病种的followup数据生成报告,同一用户只保留最新一次报告

def convert_tooktime tt

  case tt
  when '一年半或以上'
    return "18 #{tt}"
  when '已满十二个月'
    return "12 #{tt}"
  when '已满九个月'
    return "9 #{tt}"
  when '已满六个月'
    return "6 #{tt}"
  when '已满三个月'
    return "3 #{tt}"
  when '已满一个月'
    return "1 #{tt}"
  when '未满一个月', '0'
    return "0 #{tt}"
  end

  #处理只传入了月份数字的情况
  m = tt.to_i
  if m >= 0
    tt = '0 未满一个月' if m < 1
    tt = '1 已满一个月' if m >= 1
    tt = '3 已满三个月' if m >= 3
    tt = '6 已满六个月' if m >= 6
    tt = '9 已满九个月' if m >= 9
    tt = '12 已满十二月' if m >= 12
    tt = '18 一年半以上' if m >= 18
  end

  return tt

end

def convert_review rv
  case rv
  when '不好说','还不好说','未开始使用暂无'
    return "0 还不太好说"
  when '不见效'
    return "-1 看不见效果"
  when '有一定效果', '有效果', '有好转'
    return "1 有一定效果"
  when '有明显好转', '有明显好转', '有显著帮助'
    return "2 #{rv}"
  when '取得治愈', '已治愈'
    return "3 已取得治愈"
  end
  return rv
end

#修正php后端在保存json_encode数据之前没有addslashes导致去保存的unicode去斜杠问题
def fix_answers
  sql = "select id, answers from tutem_mall.eb_follow_up where answers is not null"
  queryRds(sql).each do |r|
    answers = r['answers']
    answers = answers.gsub('usage','Usage')
    answers = answers.gsub('purposes','pUrposes')
    answers = answers.gsub('foodtrust','foodtrUst')
    answers = answers.gsub('u','\u')
    answers = answers.gsub('Usage','usage')
    answers = answers.gsub('pUrposes','purposes')
    answers = answers.gsub('foodtrUst','foodtrust')
    answers = answers.gsub("\n","");
    corrected = JSON.parse(answers).to_json
    ins = "update tutem_mall.eb_follow_up set answers = '#{@rds.escape corrected}' where id = #{r['id']}";
    puts ins
    queryRds ins
  end
end

#统一answers中的JSON数据
def fix_answers_2

  sql = "select id, answers from tutem_mall.eb_follow_up where status = 1" 
  queryRds(sql).each do |r|
    answers = JSON.parse r['answers']
    usage = answers['usage'].gsub('自己及亲友','多人').gsub('孩子','家人').gsub('长辈','家人').gsub('伴侣','家人').gsub('本人','自己').gsub('朋友','亲友')
    answers.store 'usage', usage
    purposes = answers['purposes']
    if purposes.class == String
      answers.store 'purposes', [purposes]
    end
    purposes = answers['purposes']
    unified_purposes = []
    purposes.each do |p|
      p = p.gsub('难治性或不明原因癫痫','免疫性相关或难治性癫痫')
      unified_purposes += [p]
    end
    answers.store 'purposes', unified_purposes

    corrected = answers.to_json
    ins = "update tutem_mall.eb_follow_up set answers = '#{@rds.escape corrected}' where id = #{r['id']}";
    res = queryRds ins

  end
end

def report_answers
  sql = "select id, answers from tutem_mall.eb_follow_up where status = 1" 
  usages = []
  purposes = []
  queryRds(sql).each do |r|
    answers = JSON.parse r['answers']
    usages += [answers['usage']]
    purposes += answers['purposes']
  end
  ap usages.uniq
  ap purposes.uniq
end

def remove_h5_tags str
    return str.gsub('<u>','').gsub('<html>','').gsub('</u>','').gsub('</html>','');
end
#从数据库中读出记录并做相应的预处理，以便保存为excle表格
def get_followup_recs_by more_conditions

  recs = {}
  sql = "select id, uid, name as survey_name, answers, submit_time from tutem_mall.eb_follow_up where status = 1 #{more_conditions};" #e.g summary like '%癫痫'
  (queryRds(sql)).each do |q|

    uid = q['uid']
    next if uid == 6 || uid == 1 || uid == 9931 || uid == 365 || uid == 32 #跳过内部人

    id = q['id']
    submit_time = q['submit_time']
    submit_at = Time.at(submit_time).strftime('%Y-%m-%d')
    answers = q['answers']
    answers = answers.gsub("\n","")
    user_name = userList[uid]['name']
    phone = userList[uid]['phone'].to_s
    phone_part = '******' + phone[8..10].to_s
    spreader_name = userList[uid]['spreader_name']
    spreader_uid = userList[uid]['spreader_uid']

    begin
      results = JSON.parse answers
    rescue => e
      puts "ERROR:#{e.to_s}"
      puts "id: #{id}"
      exit
    end

    stores = results['stores'].nil? ? '' : results['stores'].join('|')
    usage = results['usage'] + "(#{results['gender'].to_s}#{results['age'].to_s})"
    channel = results['channel']
    purposes = results['purposes']
    purposes = [] if purposes.nil? 
    begin
        purposes = purposes.join('|')
    rescue => e
        #如果不是数组
    end
    tooktime = convert_tooktime results['tooktime']
    took_months = tooktime.split(' ')[0].to_i
    review = convert_review results['review']
    rating = review.split(' ')[0].to_i
    survey_name = q['survey_name']
    survey_name_part = survey_name[0] + '**' + survey_name[3..100].to_s
    explain = results['explain']
    advise = results['advise']
    comment = results['comment']
    other_treatment = results['other_treatment'].to_s
    therapy_before = results['therapy_before'].to_s
    canShare = 'y'
    canShare = 'n' if results['canShare'].to_s.include? '不'
    canShare = 'n' if results['canShare'].to_s.include? '否'

    docsBefore = results['related_docs'].to_s
    docsBefore = remove_h5_tags docsBefore
    docsAfterV1 = ''
    docsAfterV1 = results['pics'].join('|').to_s if !results['pics'].nil?
    docsAfterV2 = results['latest_docs'].to_s;
    docsAfter = docsAfterV1 + "#{docsAfterV2=='' ? '' : '|'}" + docsAfterV2
    docsAfter = remove_h5_tags docsAfter

    docsAfter_part = docsAfter
    docsBefore_part = docsBefore

    if canShare == 'n' && docsBefore != ''
      strlen = docsBefore.size
      docsBefore_part = docsBefore[0..strlen-4] + '***'
    end
    if canShare == 'n' && docsAfter != ''
      strlen = docsAfter.size
      docsAfter_part = docsAfter[0..strlen-4] + '***'
    end

    item = { 
        "id"=>id, "survey_name"=>survey_name, "survey_name_part"=>survey_name_part, "uid"=>uid, "user_name"=>user_name, 
        "phone"=>phone, "phone_part"=>phone_part, "channel_id"=>spreader_uid, #"spreader_name"=>spreader_name,
        "stores" => stores, "usage"=>usage, "channel"=>channel, "purposes"=>purposes, "submit_at"=>submit_at,
        "other_treatment" => other_treatment, "therapy_before" => therapy_before,
        "tooktime"=>tooktime, "review"=>review, "took_months"=>took_months, "rating"=>rating, 
        "explain"=>explain, "advise"=>advise, "comment"=>comment,
        "canShare"=>canShare,
        "docsBefore"=>docsBefore,
        "docsBefore_part"=>docsBefore_part,
        "docsAfter"=>docsAfter,
        "docsAfter_part"=>docsAfter_part
    }

=begin
    #如果是同一用户用新随访数据覆盖旧的随访数据
    if recs[uid].nil?
      recs.store uid, item
    else
      recs.store(uid, item) if id > recs[uid]['id']
    end
=end

    recs.store id, item if recs[id].nil?

  end

  return recs

end

# name: 癫痫
def gen_followup_report_for name

  conditions = " and summary like '%#{name}%';"
  conditions = '' if name.empty?

  recs = get_followup_recs_by conditions

  headers = ["survey_name","survey_name_part", "uid","phone", "phone_part", "submit_at","usage","channel","channel_id","purposes","therapy_before","tooktime","other_treatment","review","took_months", "rating", "explain","advise","comment","canShare","docsBefore", "docsBefore_part", "docsAfter", "docsAfter_part"]
  names = headers
  items = []
  recs.each { |key, item | items += [item]  }


  fn = "followup_report_#{Date.today.to_s}_for_#{name}.xls"
  save_to_excel headers,names,items,fn
  puts "#{recs.size} recs saved to #{fn}"

end

def update_followup_rating
    recs = get_followup_recs_by ''
    sqls = []
    recs.each do |key, item| 
      sqls += ["update tutem_mall.eb_follow_up set rating = #{item['rating']}, took_months = #{item['took_months']} where id = #{item['id']}"]
    end
    commitTrans sqls
end


if ARGV[0].nil?
    puts "Usage: ruby report-followup.rb keyword"
    update_followup_rating
else
    gen_followup_report_for ARGV[0] 
end
